﻿@inherits LayoutComponentBase
@inject IJSRuntime JSRuntime
@inject NavigationManager navigationManager
@inject IMenu iMenu
@inject IToolCenter iToolCenter

<Layout Class="body">

    @*菜单*@
    <Sider Collapsible Collapsed=@collapsed NoTrigger OnCollapse="OnCollapse">
        <div class="logo">
            <Image Width="40px"
                   Height="40px"
                   Preview="false"
                   Src="@userFace"
                   Class="circular"
                   Fallback="" />

            <div id="userName" class="title">
                @userName
            </div>
        </div>

        <Menu Theme="MenuTheme.Dark" Mode="MenuMode.Inline" DefaultSelectedKeys=@(new[] { "1" }) Accordion="true">
            @menuContent

            @if (File.Exists(nginxConfigPath) && isAvailableClouds)
            {
                <MenuItem Key="development" OnClick="_ => OpenDevelopment()">
                    <Icon Type="code" Theme="outline" />
                    <span>Online Dev</span>
                </MenuItem>
            }

        </Menu>

        @if (!collapsed)
        {
            <div class="version">
                iTool Gateway V1.03
            </div>
        }

    </Sider>

    @*右侧内容*@
    <Layout Class="site-layout">
        @*头部*@
        <Header Class="site-layout-background" Style="padding: 0;">

            @if (collapsed)
            {
                <Icon Type="menu-unfold" Theme="outline" Class="trigger" OnClick="toggle" />
            }
            else
            {
                <Icon Type="menu-fold" Theme="outline" Class="trigger" OnClick="toggle" />
            }

            @*<div class="searchInput">
                <Search Placeholder="Search Document" OnPressEnter="() => searchAction()" WrapperStyle="width: 200px;" @bind-Value="@searchValue" Bordered="false" ClassicSearchIcon />
            </div>*@

            <div style="float:right; margin-right:120px">
                <Menu Mode=MenuMode.Horizontal>

                    @*<MenuItem Key="mail">
                        <Badge Count="@count2">
                            <Icon Type="mail" Theme="outline" Style="font-size: 16px;"></Icon>
                        </Badge>
                        Message
                    </MenuItem>*@

                    <SubMenu TitleTemplate=@sub1Title>
                        <MenuItemGroup Title="Upgrade">
                                <MenuItem OnClick="_ => UpgradeGateway(0)">iTool Gateway</MenuItem>
                                @*<MenuItem OnClick="_ => UpgradeGateway(1)">iTool Guard</MenuItem>*@
                                <MenuItem OnClick="_ => UpgradeGateway(2)">iTool File Service</MenuItem>
                                <MenuItem OnClick="_ => UpgradeGateway(3)">iTool Cloud Connector</MenuItem>
                                <MenuItem OnClick="_ => UpgradeGateway(4)">iTool Cloud Service</MenuItem>
                            </MenuItemGroup>
                            <MenuDivider />
                        <MenuItemGroup Title="Mopnitor">
                                <MenuItem RouterLink="/">Overview</MenuItem>
                                <MenuItem RouterLink="/cluster/overview">Cluster Analysis</MenuItem>
                            </MenuItemGroup>
                            <MenuDivider />
                            <MenuItemGroup Title="Configuration">
                                <MenuItem RouterLink="/nginx">Nginx</MenuItem>
                                <MenuItem RouterLink="/itool">iTool Center</MenuItem>
                                <MenuItem RouterLink="/gateway/router">Api Gateway</MenuItem>
                            </MenuItemGroup>
                        </SubMenu>
                </Menu>
            </div>

        </Header>

        @*主内容区域*@
        <Content Class="site-layout-background" Style="margin: 24px 16px;padding: 24px;min-height: 280px;background-color: #f0f2f5;">
            @Body
        </Content>

    </Layout>
</Layout>

@*数据初始化*@
@code{
    string searchValue { get; set; }
    string userFace = "/images/face.png";
    int count2 = 2;
    string userName { get; set; }
    private string nginxConfigPath;


    RenderFragment sub1Title =
    @<Template>
        <Icon Type="setting" Theme="outline" Style="font-size: 16px;"></Icon>
        Setting
    </Template>
    ;

    RenderFragment menuContent = null;

    WindowsHelper windows { get; set; }

    bool isAvailableClouds { get; set; }

    protected override void OnInitialized()
    {
        nginxConfigPath = "/var/iTool/.nginx_gateway";

#if DEBUG
    nginxConfigPath = "D:\\iTool-Gateway-Blazor/.nginx_gateway";
#endif
    }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await base.InvokeAsync(async () =>
            {
                windows = new WindowsHelper(JSRuntime);
                var user = await windows.GetLocalStorageAsync<UserLoginResult>() ?? new UserLoginResult();
                if (user.UserKey == 0)
                {
                    navigationManager.NavigateTo("/User/Login");
                }
                else
                {
                    userName = user.UserName;
                    await this.GetMenus(user.UserKey);
                    base.StateHasChanged();
                    
                }
            });
        }

        await base.OnAfterRenderAsync(firstRender);
    }

    private async Task GetMenus(int userKey)
    {

        this.isAvailableClouds = await this.iToolCenter.IsAvailableClouds();

        var result = await iMenu.Get(new GetMenuRequset
        {
            UserKey = userKey
        });

        if (result.IsSuccessful)
        {
            var hiddenKeys = new string[] {"Monitor Panel", "Logger Center", "Nginx" };
            foreach (var item in result.Menus)
            {
                if (!isAvailableClouds && hiddenKeys.Contains(item.MenuName))
                {
                    continue;
                }

                if (item.MenuParentId == null)
                {
                    if (string.IsNullOrWhiteSpace(item.MenuUrl))
                    {
                        menuContent += this.getParentNodeElement(item, result.Menus);
                    }
                    else
                    {
                        menuContent += this.getNodeElement(item);
                    }
                }
            }
        }
    }

    private async void UpgradeGateway(int type)
    {
        var title = "Are you sure you want to upgrade?";
        var confirmResult =
            await _confirmService.Show(
                "The service will stop during the upgrade process.",
                title,
                ConfirmButtons.YesNo,
                ConfirmIcon.Warning
            );

        if (confirmResult.ToString() == "Yes")
        {
            UpgradeService upgradeService = null;
            // upgrade
            switch (type)
            {
                case 0:
                    upgradeService = new GatewayUpgradeService();
                    break;
                case 1:
                    //upgradeService = new GuardUpgradeService();
                    break;
                case 2:
                    upgradeService = new FileServiceUpgradeService();
                    break;
                case 3:
                    upgradeService = new CloudConnectorUpgradeService();
                    break;
                case 4:
                    upgradeService = new CloudServiceUpgradeService();
                    break;
            }

            if (upgradeService != null)
            {
                var task = notice.Success(new NotificationConfig
                    {
                        Message = "请求正在提交...",
                        Description = "请在稍后检查升级是否成功，如果失败请重试或者手动升级。"
                    });

                await upgradeService.UpgradeAsync();

            }
        }
    }

    private async void OpenDevelopment()
    {
        var value = File.ReadAllText(nginxConfigPath);
        NginxRequest formModel = value.TryToEntity<NginxRequest>();
        var domans = formModel.Domain.Split(",");

        string host = await windows.GetHostAsync();
        if (domans.Contains(host))
        {
            await windows.Open($"http://{host}/dev");
        }
        else
        {
            await windows.Open($"http://{domans[0]}/dev");
        }
    }

    private RenderFragment getParentNodeElement(SysMenu menu, List<SysMenu> menus)
    {
        RenderFragment nodes = null;

        RenderFragment subTitle =
    @<span>
    <Icon Type="@menu.MenuIcon" Theme="outline" />
    <span>@menu.MenuName</span>
</span>;

var list = menus.Where(item => item.MenuParentId == menu.MenuId).ToList();

@foreach (var item in list)
{
    nodes +=@<MenuItem Key="@item.MenuId.ToString()" RouterLink="@item.MenuUrl">@item.MenuName</MenuItem>;
}


return @<SubMenu Key="@menu.MenuId.ToString()" TitleTemplate=subTitle>@nodes</SubMenu>;
}

private RenderFragment getNodeElement(SysMenu menu)
{
return @<MenuItem Key="@menu.MenuId.ToString()" RouterLink="@menu.MenuUrl">
    <Icon Type="@menu.MenuIcon" Theme="outline" />
    <span>@menu.MenuName</span>
</MenuItem>;
}

}

@*导航*@
@code{

}

@*事件*@
@code {
    bool collapsed;
    void toggle()
    {
        collapsed = !collapsed;
    }
    void OnCollapse(bool isCollapsed)
    {
        Console.WriteLine($"Collapsed: {isCollapsed}");
    }
    async Task searchAction()
    {
        // 搜索方法
        await Task.Delay(100);
    }
}


<style>
    .body .trigger {
        font-size: 18px;
        line-height: 64px;
        padding: 0 24px;
        cursor: pointer;
        transition: color 0.3s;
        float: left;
    }

        .body .trigger:hover {
            color: #1890ff;
        }



    .body .site-layout-background {
        background: #fff;
    }

    .body {
        height: 100%;
    }

        .body .logo {
            margin: 10px auto 10px auto;
            text-align: center;
            padding-right: 10px;
        }

            .body .logo img {
                border-radius: 50%;
                border: 2px solid #fff;
            }

            .body .logo .title {
                color: white;
                line-height: 20px;
            }


    .ant-menu-dark {
        border-top: 2px solid #1890ff;
    }

    .ant-menu-item {
        margin-top: 0 !important;
    }

    .version {
        color: #293a50;
        text-align: center;
        padding-right: 10px;
        position: absolute;
        left: 30px;
        bottom: 30px;
    }

    .ant-badge-box {
        padding: 0 24px;
        line-height: 64px;
        float: right;
    }

        .ant-badge-box .header-icon-rigth {
            font-size: 18px;
            cursor: pointer;
            transition: color 0.3s;
        }

        .ant-badge-box:last-child {
            border-right: 1px solid #f1f1f1
        }


    .searchInput {
        width: 200px;
        float: left;
        margin-left: 100px;
    }
</style>